package com.gzh.permissionslibrary

import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat

/**
 * 动态权限申请
 */
class PermissionActivity : AppCompatActivity() {
    private var isRequireCheck: Boolean = false
    private var permission: Array<String>? = null
    private var key: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        if (intent == null || !intent.hasExtra("permission")) {
            finish()
            overridePendingTransition(0, 0)
            return
        }
        isRequireCheck = true
        permission = intent.getStringArrayExtra("permission")
        key = intent.getStringExtra("key")
    }

    override fun onResume() {
        super.onResume()
        if (isRequireCheck) {
            if (PermissionsUtil.hasPermission(this, *permission!!)) {
                permissionsGranted()
            } else {
                requestPermissions(permission!!) // 请求权限,回调时会触发onResume
                isRequireCheck = false
            }
        } else {
            isRequireCheck = true
        }
    }

    // 请求权限兼容低版本
    private fun requestPermissions(permission: Array<String>) {
        ActivityCompat.requestPermissions(
            this, permission,
            PERMISSION_REQUEST_CODE
        )
    }

    /**
     * 用户权限处理,
     * 如果全部获取, 则直接过.
     * 如果权限缺失, 则提示Dialog.
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults: IntArray
    ) {
        //部分厂商手机系统返回授权成功时，厂商可以拒绝权限，所以要用PermissionChecker二次判断
        if (requestCode == PERMISSION_REQUEST_CODE && PermissionsUtil.isGranted(*grantResults)
            && PermissionsUtil.hasPermission(this, *permissions)
        ) {
            permissionsGranted()
        } else
            permissionsDenied()
    }

    private fun permissionsDenied() {
        val listener = key?.let { PermissionsUtil.fetchListener(it) }
        listener?.permissionDenied(permission!!)
        finish()
        overridePendingTransition(0, 0)
    }

    // 全部权限均已获取
    private fun permissionsGranted() {
        val listener = key?.let { PermissionsUtil.fetchListener(it) }
        listener?.permissionGranted(permission!!)
        finish()
        overridePendingTransition(0, 0)
    }

    override fun onDestroy() {
        key?.let { PermissionsUtil.fetchListener(it) }
        super.onDestroy()
    }

    companion object {
        private const val PERMISSION_REQUEST_CODE = 64
    }
}